package com.ruoyi.back.service.impl

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.baomidou.shaun.core.context.ProfileHolder
import com.ruoyi.app.common.*
import com.ruoyi.back.domain.SystemNotice
import com.ruoyi.back.domain.Template
import com.ruoyi.back.domain.TemplateRecommend
import com.ruoyi.back.domain.dto.CheckTemplateDto
import com.ruoyi.back.domain.dto.TemplateRecommendSearchDto
import com.ruoyi.back.domain.v3.PicTemplateFaceService
import com.ruoyi.back.domain.vo.CheckStatusSumVo
import com.ruoyi.back.domain.vo.TemplateRecommendListVo
import com.ruoyi.back.enums.CheckStatusEnum
import com.ruoyi.back.mapper.TemplateRecommendMapper
import com.ruoyi.back.service.*
import com.ruoyi.common.core.page.TableSupport
import com.ruoyi.util.addPicTemplate
import com.ruoyi.util.addVideoTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TemplateRecommendServiceImpl : ServiceImpl<TemplateRecommendMapper, TemplateRecommend>(),
    TemplateRecommendService {

    @Autowired
    private lateinit var appUserService: AppUserService

    @Autowired
    private lateinit var templateService: TemplateService

    @Autowired
    private lateinit var userCollectService: UserCollectService

    @Autowired
    private lateinit var templateCategoryService: TemplateCategoryService

    @Autowired
    private lateinit var templateCommentService: TemplateCommentService

    @Autowired
    private lateinit var picTemplateFaceService: PicTemplateFaceService

    override fun saveTemplateRecommend(templateRecommend: TemplateRecommend): Data<Boolean> =
        Ok("保存成功", save(templateRecommend.apply {
            appUserService.appUserInfo(ProfileHolder.getProfile().id.toLong())?.let {
                username = it.username
                userId = it.userId
            }
        }))

    override fun templateRecommendPage(templateRecommendSearchDto: TemplateRecommendSearchDto): PageData<TemplateRecommendListVo> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(
                Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()),
                KtQueryWrapper(TemplateRecommend::class.java)
                    .like(
                        StrUtil.isNotBlank(templateRecommendSearchDto.title),
                        TemplateRecommend::title,
                        templateRecommendSearchDto.title
                    )
                    .like(
                        StrUtil.isNotBlank(templateRecommendSearchDto.userParam),
                        TemplateRecommend::userId,
                        templateRecommendSearchDto.userParam
                    )
                    .or()
                    .like(
                        StrUtil.isNotBlank(templateRecommendSearchDto.userParam),
                        TemplateRecommend::username,
                        templateRecommendSearchDto.userParam
                    )

                    .eq(TemplateRecommend::type, templateRecommendSearchDto.type)
                    .eq(
                        templateRecommendSearchDto.checkStatus != null,
                        TemplateRecommend::checkStatus,
                        templateRecommendSearchDto.checkStatus
                    )
                    .eq(
                        templateRecommendSearchDto.categoryId != null,
                        TemplateRecommend::categoryId,
                        templateRecommendSearchDto.categoryId
                    )
                    .gt(
                        StrUtil.isNotBlank(templateRecommendSearchDto.recommendBeginDate),
                        SystemNotice::sendTime,
                        templateRecommendSearchDto.recommendBeginDate.date()
                    )
                    .lt(
                        StrUtil.isNotBlank(templateRecommendSearchDto.recommendEndDate),
                        SystemNotice::sendTime,
                        templateRecommendSearchDto.recommendEndDate.date()
                    )
                    .orderByDesc(TemplateRecommend::createTime)
            ).let { page: Page<TemplateRecommend> ->
                Page<TemplateRecommendListVo>().apply {
                    BeanUtil.copyProperties(page, this)
                    records = page.records.takeIf { it.isNotEmpty() }
                        ?.run {
                            map {
                                TemplateRecommendListVo().apply {
                                    templateService.getById(it.templateId)?.let {
                                        BeanUtil.copyProperties(it, this)
                                    }
                                    it.templateId?.run {
                                        userCollectService.templateCount(this)
                                            .run {
                                                likeNum = first.toLong()
                                                collectNum = first.toLong()
                                            }
                                        useNum = templateService.getById(this)?.useNum
                                        commentNum = templateCommentService.getTemplateCheckPassComment(this)
                                    }
                                    BeanUtil.copyProperties(it, this)
                                    categoryName = templateCategoryService.getNameById(it.categoryId!!)
                                    createTime = it.createTime?.format()
                                }
                            }
                        }
                }.pageInfo()
            }
        }

    override fun checkTemplateRecommend(checkTemplateDto: CheckTemplateDto): Data<Boolean> =
        getById(checkTemplateDto.id)?.let { templateRecommend ->
            updateById(templateRecommend.apply { checkStatus = checkTemplateDto.checkStatus })
                .takeIf { it }
                ?.run {
                    if (checkTemplateDto.checkStatus == CheckStatusEnum.CHECK_PASS.code) {
                        val template = Template()
                        templateService.save(template.apply {
                            type = templateRecommend.type
                            title = templateRecommend.title
                            cover = templateRecommend.cover
                            categoryId = templateRecommend.categoryId
                            content = templateRecommend.content
                            createBy = templateRecommend.createBy
                            templateRecommend.type.takeIf { it == 2 }?.run {
                                addPicTemplate(template.content!!) { picTemplateFaces, s ->
                                    picTemplateId = s
                                    picTemplateFaces?.run { picTemplateFaceService.saveBatch(this) }
                                }
                            }
                            templateRecommend.type.takeIf { it == 1 }?.run {
                                requestId = addVideoTemplate(template.content!!)
                                requestStatus = 0
                            }
                        })
                        updateById(templateRecommend.apply {
                            templateId = template.id
                        })
                    }
                    Ok("审核成功", true)
                } ?: Fail("更新失败")
        } ?: Fail("资源不存在")

    override fun removeTemplateRecommend(ids: String): Data<Boolean> {

        ids.split(",").forEach {
            getById(it)?.run {
                templateService.removeById(templateId)
                removeById(it)
            }
        }
        return Ok("移除成功", true)
    }

    override fun offlineTemplateRecommend(id: Long): Data<Boolean> {

        getById(id)?.run {
            templateService.removeById(templateId)
            updateById(apply {
                checkStatus = CheckStatusEnum.CHECK_FAIL.code
            })
        }
        return Ok("下架成功", true)
    }

    override fun recordBoolRecommend(recordId: Long): Boolean =
        list(
            KtQueryWrapper(TemplateRecommend::class.java)
                .eq(TemplateRecommend::userRecordId, recordId)
        )
            .takeIf { it.isNotEmpty() }
            ?.run {
                any {
                    it.checkStatus == CheckStatusEnum.CHECK_PASS.code
                }

            } ?: false

    override fun checkStatusSum(type: Int): Data<CheckStatusSumVo> =
        Ok("获取统计结果成功", CheckStatusSumVo().apply {
            preCheckNum = count(
                KtQueryWrapper(TemplateRecommend::class.java)
                    .eq(TemplateRecommend::type, type)
                    .eq(TemplateRecommend::checkStatus, CheckStatusEnum.PRE_CHECK.code)
            ).toLong()
            checkSuccessNum = count(
                KtQueryWrapper(TemplateRecommend::class.java)
                    .eq(TemplateRecommend::type, type)
                    .eq(TemplateRecommend::checkStatus, CheckStatusEnum.CHECK_PASS.code)
            ).toLong()
            checkFailNum = count(
                KtQueryWrapper(TemplateRecommend::class.java)
                    .eq(TemplateRecommend::type, type)
                    .eq(TemplateRecommend::checkStatus, CheckStatusEnum.CHECK_FAIL.code)
            ).toLong()
        })
}